// 引入express框架
const express = require('express');
// 引入数据库处理模块
const mongoose = require('mongoose');
// 引入路径处理模块
const path = require('path');
// 引入session模块
var session = require('express-session');
// 处理文件上传
const formidableMiddleware = require('express-formidable');
// 统一返回数据的格式
var bodyParser = require('body-parser');
// web服务器
const app = express();
// 开放静态资源
app.use(express.static(path.join(__dirname, 'public')));
// session配置
app.use(session({
    secret: 'ushio',
    resave: false,
    saveUninitialized: false,
    cookie: {
        maxAge: 12 * 60 * 60 * 1000
    }
}));
// 处理post参数
app.use(formidableMiddleware({
    // 文件上传目录
    uploadDir: path.join(__dirname, 'public', 'uploads'),
    // 最大上传文件为2M
    maxFileSize: 2 * 1024 * 1024,
    // 保留文件扩展名
    keepExtensions: true
}));

// 跨域
app.all('/api/*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With, X_Requested_With')
    res.header('Access-Control-Allow-Credentials', true)
    res.header('SameSite', 'None')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header('X-Powered-By', ' 3.2.1')
    if (req.method == 'OPTIONS') res.sendStatus(200)
    /*让options请求快速返回*/
    else next()
});

// 初始化统一响应机制
var resextra = require('./modules/resRegular');
app.use(resextra);

// 路由
require('./routes')(app);

// 如果没有路径处理就返回 Not Found
app.use(function (req, res, next) {
    res.sendStatus(404)
});

// 返回系统监听
app.listen(354, () => console.log('服务器启动成功'));

// 数据库连接
mongoose.connect('mongodb://localhost:27017/chinchilla', {
        useNewUrlParser: true,
        useCreateIndex: true,
        useUnifiedTopology: true,
        useFindAndModify: false
    })
    .then(async () => {
        console.log('数据库连接成功');
        await require('./model/init');
        console.log('数据库初始化完毕');
    })
    .catch(() => console.log('数据库连接失败'));

// const { importOrdersFrom } = require('./model/readOrders');
// importOrdersFrom('rs637135859167845735.txt');
// const { Order } = require('./model/Order');